package com.example.app13_sqlite;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app13_sqlite.adapter.BlackNumberAdapter;
import com.example.app13_sqlite.dao.BlackNumberDao;
import com.example.app13_sqlite.entity.BlackNumber;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private ListView lvMain;

    private List<BlackNumber> blackNumberList;
    private BlackNumberDao blackNumberDao;
    private BlackNumberAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.ll_main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Log.i(TAG, "onCreate()");

        // 初始化
        blackNumberDao = new BlackNumberDao(this);

        // 初始化视图控件
        lvMain = findViewById(R.id.lv_main);
        blackNumberList = blackNumberDao.getAll();
        adapter = new BlackNumberAdapter(this, blackNumberList);
        lvMain.setAdapter(adapter);

    }

    /**
     * 添加黑名单按钮点击事件
     * @param view 发生点击事件的视图对象
     */
    public void add(View view) {
        EditText editText = new EditText(this);
        editText.setHint("请输入黑名单号");
        new AlertDialog.Builder(this)
                .setTitle("添加黑名单")
                .setView(editText)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 执行保存逻辑
                        String number = editText.getText().toString();
                        BlackNumber blackNumber = new BlackNumber(number);
                        blackNumberDao.add(blackNumber);
                        // 将数据添加至集合中的第一个元素
                        blackNumberList.add(0, blackNumber);
                        // 通知视图更新
                        adapter.notifyDataSetChanged();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
}